<template>
	<view>
		<!-- 上传图片和 附件 -->
		<u-popup zIndex="10070" :show="showUploadData" mode="center" :closeOnClickOverlay="false" round="8rpx">
			<view class="picshowContainers">
				<view class="picshowContainers_title">
					图片上传
				</view>
				<view class="picshowContainers_pic_containers">
					<u-upload :fileList="dialogImages" @afterRead="afterRead" @delete="deletePic" multiple
						:maxCount="10" :capture="['album', 'camera']" :previewFullImage="true"></u-upload>
				</view>
				<view class="picshowContainers_title">
					PDF上传:
				</view>
				<view class="picshowContainers_pic_containers">
					<u-upload @afterRead="afterfile" :maxCount="10" accept=".pdf">
						<view class="picshowContainers_btn">
							pdf上传
						</view>
					</u-upload>

				</view>
				<view class="picshowContainers_pic_list">
					<view class="picshowContainers_pic_list_item" v-for="(item, index) in pdfSrcList" :key="index">
						<view class="picshowContainers_pic_list_item_name" @tap="downloadFile(item)">
							{{item.name}} <text class="picshowContainers_pic_list_item_btn"
								@tap.stop="deletefile(index)">删除</text>
						</view>

						<u-line-progress :percentage="item.schedule" height="14rpx" activeColor="#226eff"
							v-if="item.schedule&&item.schedule!='100'"></u-line-progress>
					</view>
				</view>

			</view>
			<view class="popupGroup">
				<view class="popupGroup_btn left" @tap="comfire">
					提交
				</view>
				<view class="popupGroup_btn right" @tap="picClose">
					关闭
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: "extroUpload",
		props: ['extroUploadInfos'], //entranceType  1:专家介绍进入 2:特需会诊进入
		data() {
			return {
				TransferData: '',
				showUploadData: false,
				lookshowUploadData: false,
				dialogImages: [],
				imageURL: this.imageServiceURL, // 图片上传地址:
				srcList: [],
				pdfSrcList: [],
				imgURL: ''


			}
		},
		created() {

		},
		mounted() {
			this.picopen()
		},
		methods: {
			comfire() {
			
				let data = {
					TransferData: this.TransferData,
					imgURL: this.getImages(),
					pdfSrcList: this.getpdfSrcList()
				}
				console.log(data)
				this.$emit('comfire', data)
				this.showUploadData = false
				
			},
			getpdfSrcList() {
				let data = []
				let pdfSrcListData = this.pdfSrcList
				pdfSrcListData.forEach(ele => {
					let obj = {
						url: ele.url,
						name: ele.name,
						description: '',
						uid: ''
					}
					data.push(obj)
				})
				return data
			},
			getImages() {
				this.imgURL = ''
				this.dialogImages.forEach(ele => {
					this.imgURL += `${ele.url.slice(ele.url.indexOf('_') - 1)}|`
				})
				console.log(this.imgURL)
				return this.imgURL
			},
			// 新增文件
			async afterfile(event) {
				if (event.file.type !== 'application/pdf') {
					this.$u.toast('请上传PDF文件');
					return false; // 不允许上传
				}
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let fileListLen = this[`pdfSrcList`].length
				let item = event.file
				this[`pdfSrcList`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
				console.log(item)
				const result = await this.uploadFilePromise(item.url, fileListLen, 'file')
				console.log(fileListLen)
				let objItem = this[`pdfSrcList`][fileListLen]
				console.log(objItem)
				console.log(this[`pdfSrcList`])
				console.log(result)
				this[`pdfSrcList`].splice(fileListLen, 1, Object.assign(objItem, {
					status: 'success',
					message: '',
					url: result
				}))

			},
			// 下载
			// 下载文件资源到本地，客户端直接发起一个 HTTP GET 请求，返回文件的本地临时路径。
			downloadFile(item) {
				if (item.schedule&&item.schedule != 100) {
					this.$u.toast('请等待文件上传成功之后，再预览~');
					return false
				}
				const downloadLink = item.url;
				window.open(downloadLink, '_blank'); //h5直接进行跳转页面打开就可以了
				uni.downloadFile({ //调用uni中的下载方法
					url: item.url, //后端返回的完整路径
					success: (res) => {
						console.log(res.tempFilePath, "下载");
						if (res.statusCode === 200) {
							const tempFilePath = res.tempFilePath;
							// 显示文件
							uni.openDocument({
								filePath: tempFilePath,
								success: (res) => {
									console.log(res, '打开文件成功');
								},
							});
						}
					},
					fail: (err) => {
						console.log('下载文件失败', err);
					}
				});
			},
			//删除文件
			deletefile(index) {
				this[`pdfSrcList`].splice(index, 1)
			},
			// 删除图片
			deletePic(event) {
				this[`dialogImages`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {

				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`dialogImages`].length
				console.log(fileListLen)
				lists.map((item) => {
					this[`dialogImages`].push({
						...item,
						schedule: 0,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, i, 'img')
					console.log(fileListLen)
					let item = this[`dialogImages`][fileListLen]
					console.log(result)
					this[`dialogImages`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						schedule: 100,
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, index, type) {
				let that = this
				return new Promise((resolve, reject) => {
					let uploadTask = uni.uploadFile({
						url: `${that.imageURL}/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {

						},
						success: (res) => {
							console.log(res)
							let data = JSON.parse(res.data)
							setTimeout(() => {
								console.log(data.url)
								resolve(data.url)
							}, 1000)
						}
					});
					uploadTask.onProgressUpdate((res) => {
						// console.log('上传进度' + res.progress);
						// console.log('已经上传的数据长度' + res.totalBytesSent);
						// console.log('预期需要上传的数据总长度' + res
						// 	.totalBytesExpectedToSend);
						let item
						if (type == 'img') { //图片上传
							item = that[`dialogImages`][index]
							that[`dialogImages`].splice(index, 1, Object.assign(item, {
								status: 'success',
								message: '',
								schedule: res.progress,

							}))
						} else {
							item = that[`pdfSrcList`][index]

							that[`pdfSrcList`].splice(index, 1, Object.assign(item, {
								status: 'success',
								message: '',
								schedule: res.progress,

							}))
						}
						// 测试条件，取消上传任务。
						if (res.progress > 50000) {
							uploadTask.abort();
						}
					});

				})
			},
			picopen() { //图片上传弹窗打开时
				let item = this.extroUploadInfos
				this.TransferData = item.ids?item.ids:item.id
				this.dialogImages = []
				this.pdfSrcList = []
				this.srcList = []
				if (item.url||item.resultUrl) {
					this.imgURL = item.url?item.url:item.resultUrl
					const imgList = this.imgURL.split('|')
					const formatList = imgList.slice(0, -1)
					formatList.forEach(ele => {
						this.dialogImages.push({
							name: 'img',
							url: this.imageURL + ele
						})
						this.srcList.push(this.imageURL + ele)
					})
				}
				if (item.pdfUrl) {
					this.pdfSrcList = JSON.parse(item.pdfUrl)
				}
				this.showUploadData = true
			},
			picClose() { //图片上传弹窗关闭
				this.showUploadData = false
				this.$emit('closeedextroUploadStatus')

			},


		}
	}
</script>

<style lang="scss" scoped>
	// 上传弹窗
	.picshowContainers {
		width: 90vw;
		padding: 24rpx;
		max-height: 70vh;
		overflow: hidden;
		overflow-y: auto;

		&_title {
			font-size: 30rpx;
			font-weight: 700;
			line-height: 44rpx;
		}

		&_pic {
			&_containers {
				margin-top: 16rpx;
			}

			&_list {
				&_item {
					&_name {
						font-size: 24rpx;
						line-height: 40rpx;
					}

					&_btn {
						color: red;
						margin-left: 12rpx;
						cursor: pointer;
					}
				}
			}
		}

		&_btn {
			background: #226eff;
			color: #fff;
			padding: 0 16rpx;
			font-size: 26rpx;
			line-height: 44rpx;
		}
	}

	.popupGroup {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
		padding-bottom: 24rpx;

		&_btn {
			font-size: 26rpx;
			padding: 8rpx 16rpx;
			border: 2rpx solid #ddd;
			border-radius: 6rpx;
		}

		&_btn.left {
			color: #fff;
			background: #226eff;
			border: 2rpx solid #226eff;
		}

		&_btn.right {
			margin-left: 24rpx;
		}
	}
</style>